package com.lai.qq.admin.exception;


import com.lai.qq.admin.biz.res.RebackInfoResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;

/**
 * 异常处理器
 *
 */
@RestControllerAdvice
@Slf4j
public class CommonExceptionHandler {




	@ExceptionHandler(MethodArgumentNotValidException.class)
	public RebackInfoResult<?> exception(MethodArgumentNotValidException e) {
		BindingResult bindingResult = e.getBindingResult();
		List<ObjectError> allErrors = bindingResult.getAllErrors();
		StringBuffer buf = new StringBuffer();
		allErrors.forEach(objectError -> {
			FieldError fieldError = (FieldError)objectError;
			buf.append(fieldError.getDefaultMessage()).append(",");
		});
		/*List<ErrorMsg> errorMsgs = new ArrayList<>();
		allErrors.forEach(objectError -> {
			ErrorMsg errorMsg = new ErrorMsg();
			FieldError fieldError = (FieldError)objectError;
			errorMsg.setField(fieldError.getField());
			errorMsg.setObjectName(fieldError.getObjectName());
			errorMsg.setMessage(fieldError.getDefaultMessage());
			errorMsgs.add(errorMsg);
		});*/
		return new RebackInfoResult().failure(buf.substring(0, buf.length()-1));
	}

	/**
	 * 方法参数校验
	 * @param e
	 * @return
	 */
	@ExceptionHandler(MissingServletRequestParameterException.class)
	public RebackInfoResult<?>  handleMethodArgumentNotValidException(MissingServletRequestParameterException e) {
		log.error(e.getMessage(), e);
		return new RebackInfoResult().failure(e.getParameterName()+"不能为空");
	}

}
